<template>
  <div class="network-access-management">
        <div class="flex gap-20px">
           <div class="w-50% flex-1 container_left ">
              <MCard class="container_left_top m-b-40px">
                <template #header>      
                  <div class="title_box">
                    <img :src="networkAccessManagementBg2" alt="">
                    <span class="text-14px">{{ t('functionService.network_access_process_label') }}</span>
                  </div>
                </template>
                <div class="container_left_top_content p-l-15px p-t-10px p-r-10px">
                  <!--  <div class="label_box" v-for="item in basebandAccessStates" :key="item.label">
                      <div class="label">{{ item.label }}</div>
                      <div class="label">{{ item.status==='success' ? t('functionService.connected_label') : t('functionService.not_connected_label') }}</div>
                   </div> -->
                   <div class="label_box">
                      <div class="label">{{ t('functionService.auto_network_access_state_label') }}</div>
                      <div class="label">{{ state }}</div>
                   </div>
                   <div class="label_box">
                    <div class="label">{{ t('functionService.ka_init_state_label') }}</div>
                    <div class="label">{{ kaInitState }}</div>
                   </div>
                <div v-for="item in dnnInfoList" :key="item.type">
                <div class="label_box">
                 <div class="label">{{ dnnEnum[item.type] }}</div>
                  <div class="label">{{ item.connect === 'on' ? t('functionService.connected_status_label') : t('functionService.not_connected_status_label') }}</div>
                  </div>
                  <div class="label_box">
                   <div class="label">{{ dnnIpEnum[item.type] }}</div>
                    <div class="label">{{ item.dnn_ip }}</div>
                 </div>
                </div>
                </div>
              </MCard>
              <MCard class="container_left_bottom m-b-40px">
                <template #header>
                  <div class="title_box">
                    <img :src="networkAccessManagementBg2" alt="">
                    <span class="text-14px">{{ t('functionService.auto_beam_search_label') }}</span>
                  </div>
                </template>
                 <div class="flex justify-between p-l-15px p-t-10px p-r-10px">
                    <div class="text-14px">{{ t('functionService.auto_beam_search_label')}}({{ t('functionService.reboot_record_label') }})</div>
                    <div>
                      <MSelect 
                      v-bind="autoNetworkAccessConfig"
                      v-model="isAuto"
                      />
                      <div class="flex justify-end m-t-10px">
                        <div class="global_btn" v-globalLoading="setAutoNetworkAccess" :class="{ 'is-loading': autoSetLoading }">
                          <el-icon class="m-r-5px"><Setting /></el-icon>
                          {{ t('functionService.set_label') }}
                        </div>
                      </div>                  
                    </div>
                 </div>
              </MCard>
              <TemplateBox 
              :title="beamSelectConfig.title"
              :subTitle="beamSelectConfig.subTitle"
              :btns="beamSelectConfig.btns"
              :component="beamSelectConfig.component"
              :optionsConfig="beamSelectOptions"
              />
              <MCard>
                <template #header>
                  <div class="title_box">
                    <img :src="networkAccessManagementBg2" alt="">
                    <span class="text-14px">{{beamSelectConfig.title}}</span>
                  </div>
                </template>
                <div class="container_left_bottom_content p-l-15px p-t-20px p-r-10px">
                  <div class="flex justify-between items-center m-b-20px">
                    <div class="label text-14px">{{ beamSelectConfig.subTitle}}</div>
                    <MSelect 
                    v-bind="beamSelectOptions"
                    v-model="beamSelectOptions.baseband_id"
                    />
                  </div>
                  <div class="flex justify-between items-center" v-if="basebandNum>1">
                    <div class="label text-14px">选择当前CP</div>
                    <MSelect 
                    v-bind="cpConfigList"
                    v-model="cpConfigList.cp_id"
                    />
                  </div>
                </div>
                <div class="flex justify-end m-t-10px p-r-10px">
                  <div class="global_btn" v-globalLoading="handleBeamSelect" >
                    <el-icon class="m-r-5px"><Setting /></el-icon>
                    {{ t('functionService.set_label') }}
                  </div>
                </div>
              </MCard>
          <!--     <MCard>
                <template #header>
                  <div class="title_box">
                    <img :src="networkAccessManagementBg2" alt="">
                    <span class="text-14px">{{ t('functionService.apn_config_label') }}</span>
                  </div>
                </template>
                <div class="container_left_bottom_content p-l-15px p-t-20px p-r-10px">
                <el-form
                :inline="true"
                ref="appConfigRef"
                :model="apnConfig"
                :rules="appConfigFormRules"
                hide-required-asterisk
                >
                  <el-form-item  label="apn" class="tech-form-item" prop="apn">
                    <el-input v-model="apnConfig.apn" />
                  </el-form-item>
                  <el-form-item  label="apnId" class="tech-form-item" prop="apnId">
                    <el-input v-model="apnConfig.apnId" />
                  </el-form-item>
                  <el-form-item class="tech-form-item">
                    <div class="global_btn" v-globalLoading="addApnConfig" >                 
                      <el-icon class="m-r-5px"><Plus /></el-icon>
                      {{ t('functionService.add_apn_label') }}
                    </div>
                  </el-form-item>
                </el-form>                 
                </div>
                <div class="m-t-30px">
                  <el-table :data="appConfigList" max-height="150px">
                    <el-table-column label="apn" prop="apn" />
                    <el-table-column label="操作">
                      <template #default="scope">
                        <div class="global_btn" v-globalLoading="deleteApnConfig.bind(null,scope.row)">
                          <el-icon class="m-r-5px"><Delete /></el-icon>
                          {{ t('functionService.delete_apn_label') }}
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </MCard> -->
             <!--  <MCard>
                <template #header>
                  <div class="title_box">
                    <img :src="networkAccessManagementBg2" alt="">
                    <span class="text-14px">{{ t('functionService.frequency_point_management_label') }}</span>
                  </div>
                </template>
                <div class='container_left_bottom_content p-l-15px p-t-20px p-r-10px'>
                    <div class="flex gap-20px items-center">
                       <span>{{ t('functionService.select_satellite_label') }}</span>
                       <MSelect
                       v-bind="stateSelectConfig"
                       v-model="stateSelectNum"
                       />
                       <div class="global_btn" v-globalLoading="handleSetFrequencyPoint" >
                        <el-icon class="m-r-5px"><Setting /></el-icon>
                        {{ t('functionService.set_label') }}
                       </div>
                    </div>
                    <div class="flex gap-20px items-center m-t-20px">
                        <span>{{ t('functionService.auto_beam_label') }}</span>
                        <el-switch v-model="autoBeam" />
                        <div 
                        v-btnPermission="['freqAdd']"
                        class="global_btn m-l-auto" 
                        v-globalLoading="handleAddBeam" >
                          <el-icon class="m-r-5px"><Plus /></el-icon>
                          {{ t('functionService.add_label') }}
                        </div>
                    </div>
                    <div class="m-t-20px">
                      <el-table
                    :data="beamList"
                    max-height="300px"
                    :key="freqTableKey"
                    >
                      <el-table-column :label="t('functionService.beam_name_label')" prop="kd_name" align="center" />
                      <el-table-column :label="t('functionService.down_frequency_label')" align="center">
                        <template #default="{ row }">
                          {{ (row.downlink_freq) }}
                        </template>
                      </el-table-column>
                      <el-table-column :label="t('functionService.ssb_position_label')" prop="ssb_position" align="center" />
                      <el-table-column :label="t('functionService.up_frequency_label')" align="center">
                        <template #default="{ row }">
                          {{ (row.uplink_freq) }}
                        </template>
                      </el-table-column>
                      <el-table-column :label="t('functionService.bandwidth_label')" align="center">
                        <template #default="{ row }">
                          {{ row.bandwidth }} 
                        </template>
                      </el-table-column>
                      <el-table-column 
                        :label="hasOperationPermission ? t('functionService.operation_label') : ''"  
                        :width="hasOperationPermission ? '180' : '0'" 
                        align="center"
                      >
                        <template #default="{ row }">
                          <div class="flex justify-center gap-10px" v-if="hasOperationPermission">
                            <div class="global_btn" @click="handleEditBeam(row)">
                              {{ t('networkConfig.edit_label') }}
                            </div>
                            <div class="global_btn_cancel" v-globalLoading="handleDeleteBeam.bind(null,row)">
                              {{ t('networkConfig.delete_label') }}
                            </div>
                          </div>
                        </template>
                      </el-table-column>
                    </el-table>
                    </div>
                </div>
              </MCard>    -->              
           </div>
           <div class="w-50% flex-1 container_right">
            <!-- 选星配置 -->
            <MCard class="p-10px m-b-40px">
              <template #header>
                <div class="title_box">
                  <img :src="networkAccessManagementBg2" alt="">
                  <span class="text-14px">{{ t('functionService.state_select_config_label') }}</span>
                </div>
              </template>
              <div class="container_left_bottom_content p-l-15px p-t-20px p-r-10px">
                <div class="flex justify-between items-center">
                  <div class="label text-14px">{{ t('functionService.select_star_label') }}</div>
                  <MSelect 
                  v-bind="stateSelectConfig"
                  v-model="stateSelectNum"
                  />
                </div>
                <div class="flex justify-end m-t-10px">
                  <div class="global_btn" v-globalLoading="setStateSelectConfig" >
                    <el-icon class="m-r-5px"><Setting /></el-icon>
                    {{ t('functionService.set_label') }}
                  </div>
                </div>
              </div>
            </MCard>
            <TemplateBox 
            :title="accessConfig.title" 
            :optionsConfig="basebandConfig" 
            :subTitle="accessConfig.subTitle"
            :btns="accessConfig.btns"
            :component="accessConfig.component"
            />
            <div class="m-t-40px">
              <TemplateBox 
              :title="satelliteLongitudeconfigure.title"
              :subTitle="satelliteLongitudeconfigure.subTitle"
              :btns="satelliteLongitudeconfigure.btns"
              :component="satelliteLongitudeconfigure.component"
              v-model:inputNumber="satelliteLongitude"
              />
            </div>
            <div class="m-t-40px">
              <TemplateBox 
              :title="beaconFrequencyConfig.title"
              :subTitle="beaconFrequencyConfig.subTitle"
              :btns="beaconFrequencyConfig.btns"
              :component="beaconFrequencyConfig.component"
              v-model:inputNumber="beaconFrequencyValue"
              />
            </div>
            <MCard class="m-t-40px p-10px">
              <template #header>
                <div class="title_box">
                  <img :src="networkAccessManagementBg2" alt="">
                  <span class="text-14px">{{ t('functionService.dnn_config_label') }}</span>
                </div>
              </template>
              <div>
              
              </div>
              <div class="container_left_bottom_content p-l-15px p-t-20px p-r-10px">
                <div v-for="item in dnnConfigs" :key="item.type" class="flex justify-between m-b-20px items-center">
                  <span class="text-14px">{{ dnnEnum[item.type] }}</span>
                  <div>
                    <MSelect 
                    v-bind="item"
                    v-model="item.modelValue"
                    />                  
                  </div>
                </div>
                <div class="flex justify-end m-t-10px">
                  <div class="global_btn" v-globalLoading="setDnnConfig.bind(null,setDnnBtnConfig)" >
                    <el-icon class="m-r-5px"><Setting /></el-icon>
                    {{ setDnnBtnConfig.label }}
                  </div>
                </div>
              </div>
            </MCard>
           </div>
       </div>
       <Dialog v-bind="beamDiaLog" v-model:dialogVisible="beamDiaLog.dialogVisible" >
        <template #content>
          <div class="p-20px">
            <el-form 
              ref="beamEditFormRef"
              :model="beamEditForm"
              :rules="beamEditFormRules"
              label-width="120px"
              class="tech-form"
              hide-required-asterisk
            >
              <el-form-item :label="t('functionService.beam_name_label')" prop="kd_name" class="tech-form-item">
                <el-input v-model="beamEditForm.kd_name" />
              </el-form-item>
              <el-form-item :label="t('functionService.down_frequency_label')" prop="downlink_freq" class="tech-form-item">
                <el-input-number 
                  v-model="beamEditForm.downlink_freq" 
                  :precision="0" 
                  :min="1"
                  style="width: 100%;"
                />
              </el-form-item>
              <el-form-item :label="t('functionService.ssb_position_label')" prop="ssb_position" class="tech-form-item">
                <el-input-number 
                  v-model="beamEditForm.ssb_position" 
                  :precision="0" 
                  :min="0"
                  style="width: 100%;"
                />
              </el-form-item>
              <el-form-item :label="t('functionService.up_frequency_label')" prop="uplink_freq" class="tech-form-item">
                <el-input-number 
                  v-model="beamEditForm.uplink_freq" 
                  :precision="0" 
                  :min="1"
                  style="width: 100%;"
                />
              </el-form-item>
              <el-form-item :label="t('functionService.bandwidth_label')" prop="bandwidth" class="tech-form-item">
                <el-input-number 
                  v-model="beamEditForm.bandwidth" 
                  :precision="0" 
                  :min="1"
                  :max="100"
                  style="width: 100%;"
                />
              </el-form-item>
            </el-form>
          </div>
        </template>
        <template #footer>
          <div class="flex justify-center gap-20px">
            <div class="global_btn" v-globalLoading="saveBeamEdit" style="width: 100px;">
              {{ t('functionService.save_label') }}
            </div>
            <div class="global_btn_cancel" @click="beamDiaLog.dialogVisible = false" style="width: 100px;">
              {{ t('functionService.cancel_label') }}
            </div>
          </div>
        </template>
       </Dialog>
  </div>
</template>

<script  lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'networkAccessManagement',
})
</script>

<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import { NetworkAccessManagementApi } from '@/api/networkAccessManagement'
import {ElNotificationFn } from '@/utils/computedUtils'
import { BasebandApi } from '@/api/basebandControl'
import { BasicConfigApi } from '@/api/basicConfig'
import { DnnConfigApi } from '@/api/dnnConfig'
import networkAccessManagementBg2 from '@/assets/imgs/networkAccessManagement-bg2.png'
import TemplateBox from './components/TemplateBox.vue'
import { useTodStore } from '@/stores/todStore'
import { useUserInfoStore } from '@/stores/userInfo'
import { storeToRefs } from 'pinia'
const todStore = useTodStore()
const {EastType} = storeToRefs(todStore)
const userInfoStore = useUserInfoStore()
const {basebandNum} = storeToRefs(userInfoStore)
const { t } = useI18n()
const basebandAccessStates = ref<any>([])
const dnnInfoList = ref<any[]>([])
const hasOperationPermission = computed(() => {
  return userInfoStore.btnPermissions.some(perm => ['freqEdit', 'freqDelete','freqAdd'].includes(perm))
})
const dnnEnum = computed<any>(()=>({
  'internet':t('functionService.ip_business_dnn_state_label'),
  'xwtj':t('functionService.suite_management_dnn_state_label'),
  'caa':t('functionService.caa_dnn_state_label')
}))
const dnnIpEnum = computed<any>(()=>({
  'internet':t('functionService.business_ip_address_label'),
  'xwtj':t('functionService.management_ip_address_label'),
  'caa':t('functionService.caa_ip_address_label')
}))
async function getDnnInfo() {
  try {
    const { data } = await DnnConfigApi.reqGetDnnInfo()
    const priorityTypes = ['internet', 'xwtj',"caa"]
    const priorityDnns = data.list.filter((item:any)=>priorityTypes.includes(item.type))
    priorityDnns.sort((a:any,b:any)=>{
      return priorityTypes.indexOf(a.type) - priorityTypes.indexOf(b.type)
    })
    dnnInfoList.value = priorityDnns
  } catch (error) {
    console.error('获取DNN信息失败:', error)
    ElNotificationFn('error', t('functionService.refresh_failure_label'))
  }
}
const isAuto = ref(0)
const autoNetworkAccessConfig = computed(()=> ({
  options:[
    {
      label:t('functionService.open_label'),
      value:1
    },
    {
      label:t('functionService.close_label'),
      value:0
    }
  ],
  width:'300px',
}))
const autoRefreshLoading = ref(false)
const autoSetLoading = ref(false)
async function refreshAutoNetworkAccess(){
      try {
        autoRefreshLoading.value = true
        await getAutoNetworkAccessStatus()
        ElNotificationFn('success', t('functionService.refresh_success_label'))
      } catch (error) {
    ElNotificationFn('error', t('functionService.refresh_failure_label'))
  } finally {
    autoRefreshLoading.value = false
  }
}
async function setAutoNetworkAccess(){
  try {
    autoSetLoading.value = true
    await NetworkAccessManagementApi.reqPostAutoNetworkAccess({
      is_auto:isAuto.value
    })
    ElNotificationFn('success', t('functionService.set_success_label'))
  } catch (error) {
    ElNotificationFn('error', t('functionService.set_failure_label'))
  } finally {
    autoSetLoading.value = false
  }
}
const btnLoadingStates = ref<any>({
  0: false,
  1: false  
})
const accessConfig = computed(()=>  ({
  title:t('functionService.auto_network_access_label'),
  subTitle:t('functionService.baseband_control_label'),
  component:'select',
  btns:[
    {
      label:t('functionService.network_access_label'),
      value:0,
      component:'TopRight',
      click:handleNetworkAccessOpen,
      loading:btnLoadingStates.value[0],
      class:'global_btn'
    },
    {
      label:t('functionService.network_access_exit_label'),
      value:1,
      component:'BottomLeft',
      click:handleNetworkAccessClose,
      loading:btnLoadingStates.value[1],
      class:'global_btn_cancel',
      color:'#e75e34'
    }
  ]
}))
const btnLongitudeStates = ref<any>({
  0:false,
  1:false
})
const satelliteLongitude = ref(152.8)
const satelliteLongitudeconfigure = computed(()=> (  {
  title:t('functionService.satellite_longitude_label'),
  subTitle:t('functionService.satellite_longitude'),
  component:'inputNumber',
  btns:[
    {
      label:t('functionService.satellite_longitude_send_label'),
      value:0,
      component:'Position',
      click:satelliteLongitudeSend,
      loading:btnLongitudeStates.value[0],
      class:'global_btn'
    },

  ],
}))
const dnnConfigs = ref<any>([])
const setDnnBtnConfig = ref<any>({
  label:t('functionService.set_label'),
  value:0,
  component:'Setting',
  type:'primary',
  color:'#1b3a63',
  loading:false
})
async function getDnnConfig(){
  const {data} = await BasicConfigApi.reqGetDnnConfig()
  dnnConfigs.value =  data.apn_get.filter((item:any)=>item.type === 'internet'||item.type === 'xwtj'||item.type === 'caa').map((item:any)=>{
    return {
       type:item.type,
       modelValue:item.using_apn,
       options: [],
       width:'300px',
    }
  })
  dnnConfigs.value.sort((a:any)=>{
    return a.type === 'internet' ? -1 : 1
  })
  await getDnnList()
}
async function setDnnConfig(btn:any){
  try {
    btn.loading = true
    const apn_set = dnnConfigs.value.map((item:any)=>{
      return {
        type:item.type,
        using_apn:item.modelValue
      }
    })
    await BasicConfigApi.reqSetDnnConfig({
      apn_set,
    })
    await getDnnList()
    ElNotificationFn('success', t('functionService.set_success_label'))
  } catch (error) {
    ElNotificationFn('error', t('functionService.set_failure_label'))
  } finally {
    btn.loading = false
  }
}
async function getDnnList(){
  const {data} = await BasicConfigApi.reqGetDnnList()
  appConfigList.value = data.list_get
  dnnConfigs.value = dnnConfigs.value.map((item:any)=>{
    item.options = data.list_get.map((item:any)=>{
      return {
        label:item.apn,
        value:item.apn
      }
    })
    return item
  })
}
const networkAccessConfig = ref({
   is_auto:0,
   loading:false
})
async function networkAccessSwitchChange(value: number) {
  networkAccessConfig.value.loading = true
  try {
    await NetworkAccessManagementApi.reqPostAutoNetworkAccess({
      is_auto: value 
    })
    const successMsg = value === 1 
      ? t('functionService.open_success_label')
      : t('functionService.close_success_label')
    ElNotificationFn('success', successMsg)
  } catch (error) {
    const errorMsg = value === 1
      ? t('functionService.open_failure_label') 
      : t('functionService.close_failure_label')
    ElNotificationFn('error', errorMsg)
    networkAccessConfig.value.is_auto = value === 1 ? 0 : 1
  } finally {
    networkAccessConfig.value.loading = false
  }
}
const networkAccessButtonConfig = ref({
  at:"at+cfun=1",
  loading:false
})
const networkAccessCloseButtonConfig = ref({
  at:"at+cfun=0",
  loading:false
})
async function handleNetworkAccessOpen(btn:any){
  try {
    btnLoadingStates.value[btn.value] = true
    await BasebandApi.reqSendCommand({
      at:networkAccessButtonConfig.value.at,
      id:basebandConfig.value.baseband_id
    })
    ElNotificationFn('success', t('functionService.network_access_open_success_label'))
  } catch (error) {
    ElNotificationFn('error', t('functionService.network_access_open_failure_label'))
  }finally{
    btnLoadingStates.value[btn.value] = false
  }
}
async function handleNetworkAccessClose(btn:any){
  try {
    btnLoadingStates.value[btn.value] = true
  await BasebandApi.reqSendCommand({
    at:networkAccessCloseButtonConfig.value.at,
    id:basebandConfig.value.baseband_id
  })
  ElNotificationFn('success', t('functionService.network_access_close_success_label'))
  } catch (error) {
    ElNotificationFn('error', t('functionService.network_access_close_failure_label'))
  }finally{
    btnLoadingStates.value[btn.value] = false
  }
}
async function satelliteLongitudeSend(btn:any){
  try {
    btnLongitudeStates.value[btn.value] = true
    await NetworkAccessManagementApi.reqPostSatelliteLongitude({
      lon_store:satelliteLongitude.value
    })
    ElNotificationFn('success', t('functionService.set_success_label'))
    getSatelliteLongitude()
  } catch (error) {
    ElNotificationFn('error', t('functionService.set_failure_label'))
  } finally {
    btnLongitudeStates.value[btn.value] = false
  }
}
async function getSatelliteLongitude(){
  const {data} = await NetworkAccessManagementApi.reqGetSatelliteLongitude()
  satelliteLongitude.value = data.lon_store
}
async function getAutoNetworkAccessStatus(){
  const {data} = await NetworkAccessManagementApi.reqGetAutoNetworkAccessStatus()
  isAuto.value = data.is_auto
}
const basebandConfig = ref<any>({
  options:[],
  placeholder:t('functionService.baseband_name_label'),
  baseband_id:0,
  width:'300px'
})
const cpConfigList = ref<any>({
  options:[],
  placeholder:t('functionService.cp_name_label'),
  cp_id:0,
  width:'300px'
})
async function getBasebandInfo(){
  const {data} = await BasebandApi.reqGetBasebandInfo()
  basebandConfig.value.options = data.info.map((item:any)=>{
    return {
      label:item.name,
      value:item.id
    }
  })
  cpConfigList.value.options = data.info.map((item:any)=>{
    return {
      label:item.name,
      value:item.id
    }
  })
  cpConfigList.value.cp_id = data.info[0].id
  basebandAccessStates.value = data.info.map((item:any)=>{
    return {
      label:item.name,
      status:item.status
    }
  })
}
const state = ref('') // 入网状态
const kaInitState = ref('') // 广播搜索状态
const networkAccessState:any = {
  0:'等待中', 
  1:'平台初始化失败',
  2:'天线初始化失败',
  3:'定位初始化失败',
  4:'对星失败',
  5:'自动入网中',
  6:'自动入网已关闭',
  7:'已入网'
}
const networkkaInitStateStatus:any = {
  0:'射频初始化失败',
  1:'射频初始化完成',
  2:'接收广播成功',
}
async function getStatus(){
  const {data} = await NetworkAccessManagementApi.reqGetStatus()
  state.value = networkAccessState[data.state]
  kaInitState.value = networkkaInitStateStatus[data.ka_init_state]
}
const stateSelectNum = ref()
const stateSelectConfig = computed(()=>({
  options:[
    {
      label:t('functionService.auto_label'),
      value:0
    },
    {
      label:t('functionService.africa_star_label'),
      value:1
    },
    {
      label:t('functionService.asia_star_label'),
      value:2
    },
    {
      label:t('functionService.america_star_label'),
      value:3
    },   
  ],
  placeholder:t('functionService.select_star_label'),
  width:'300px'
}))
async function getStateSelectConfig(){
  const {data} = await NetworkAccessManagementApi.reqGetStateSelectConfig()
  stateSelectNum.value = data.sate
}
const starEastLongitudeConfig:any = {
  1:{
    1:33.6,
    2:153.1,
    3:77.2
  },
  2:{
    1:-33.6,
    2:-153.1,
    3:-77.2
  }
}
async function setStateSelectConfig(){
  await NetworkAccessManagementApi.reqSetStateSelectConfig({
    sate:stateSelectNum.value
  })
  if(stateSelectNum.value === 0){
    ElNotificationFn('success', t('functionService.set_success_label'))
    return  
  }
  await NetworkAccessManagementApi.reqPostSatelliteLongitude({
    lon_store:starEastLongitudeConfig[EastType.value][stateSelectNum.value]
  })

 await getSatelliteLongitude()
 ElNotificationFn('success', t('functionService.set_success_label'))
}
const beamSelectOptions = ref<any>({
  options:Array.from({length:10},(_,index)=>{
    return {
      label:`${index}`,
      value:"AT^TEST=78,"+index
    }
  }),
  baseband_id:0,
  width:'300px',
  placeholder:t('functionService.select_beam_label')
})
const beamSelectConfig = computed(()=>({
  title:t('functionService.beam_select_label'),
  subTitle:t('functionService.beam_index_select_label')+`(${t('functionService.disable_auto_search_label')})`,
  component:'select',
  btns:[
    {
      label:t('functionService.set_label'),
      value:0,
      component:'Setting',
      type:'primary',
      loading:false,
      class:'global_btn',
      click:handleBeamSelect
    }
  ]
}))
async function handleBeamSelect(){
  await BasebandApi.reqSendCommand({
    at:beamSelectOptions.value.baseband_id,
    id:cpConfigList.value.cp_id
  })
  const index = beamSelectOptions.value.options.findIndex((item:any)=>item.value === beamSelectOptions.value.baseband_id)
  await NetworkAccessManagementApi.reqSetBeamConfig({
    beam:index,
  })
  ElNotificationFn('success', t('functionService.set_success_label'))
}
async function getBeamConfig(){
  const {data} = await NetworkAccessManagementApi.reqGetBeamConfig()
  beamSelectOptions.value.baseband_id = beamSelectOptions.value.options[data.beam].value
}
const autoBeam = ref(false)
const freqList = ref<any>([])
const freqTableKey = ref(0)
const beamList = ref<any>([])
const beamDiaLog = ref<any>({
  title: t('functionService.edit_beam_label'),
  width: '500',
  dialogVisible: false,
  top: "5vh",
  changeType: "beam"
})
const beamEditForm = ref<any>({
  id: '',
  kd_name: '',
  downlink_freq: 0,
  ssb_position: 0,
  uplink_freq: 0,
  downlink_bdc: 0,
  uplink_buc: 0,
  sib1_downlink: 0,
  bandwidth: 0
})
const beamEditFormRules = ref<any>({
  kd_name: [
    { required: true, message: t('functionService.beam_name_required'), trigger: 'blur' }
  ],
  downlink_freq: [
    { required: true, message: t('functionService.down_frequency_required'), trigger: 'blur' },
    { type: 'number', min: 1, message: t('functionService.frequency_invalid'), trigger: 'blur' }
  ],
  uplink_freq: [
    { required: true, message: t('functionService.up_frequency_required'), trigger: 'blur' },
    { type: 'number', min: 1, message: t('functionService.frequency_invalid'), trigger: 'blur' }
  ],
  ssb_position: [
    { required: true, message: t('functionService.ssb_position_required'), trigger: 'blur' },
    { type: 'number', min: 0, message: t('functionService.ssb_position_invalid'), trigger: 'blur' }
  ],
  bandwidth: [
    { required: true, message: t('functionService.bandwidth_required'), trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: t('functionService.bandwidth_invalid'), trigger: 'blur' }
  ]
})
const beamEditFormRef = ref<any>(null)
async function getFrequencyPoint(){
  try {
    const {data} = await NetworkAccessManagementApi.reqGetFrequencyPoint()
    freqList.value = data.freq
    handleSetFrequencyPoint()
  } catch (error) {
    return new Promise((_,reject)=>{
      reject(error)
    })
  }
}
async function handleSetFrequencyPoint(){
  beamList.value = []
  const freqItem = freqList.value.find((item:any)=>item.sat === stateSelectNum.value)
  if(freqItem){
    console.log(freqItem,"freqItem");
    beamList.value =  freqItem.freq_info
  }else{
    let arr:any = []
   freqList.value.forEach((item:any)=>{
    item.freq_info.forEach((item:any)=>{
      arr.push({
        ...item,
      })
    })
   })
   beamList.value = arr
  }
}
const handleEditBeam = (row: any) => {
  beamDiaLog.value.dialogVisible = true;
  beamDiaLog.value.title = t('functionService.edit_beam_label');
  beamEditForm.value = {
    id: row.id,
    kd_name: row.kd_name || '',
    downlink_freq: row.downlink_freq || 0,
    ssb_position: row.ssb_position || 0,
    uplink_freq: row.uplink_freq || 0,
    downlink_bdc: row.downlink_bdc || 0,
    uplink_buc: row.uplink_buc || 0,
    sib1_downlink: row.sib1_downlink || 0,
    bandwidth: row.bandwidth || 0
  };
};
async function handleDeleteBeam(row: any) {
  try {
    await NetworkAccessManagementApi.reqDeleteFrequencyPoint({
      id:row.id,
      sat:stateSelectNum.value
  })
  await getFrequencyPoint()
  freqTableKey.value++
  ElNotificationFn('success', t('functionService.delete_success_label'))
  } catch (error) {
    ElNotificationFn('error', t('functionService.delete_failure_label'))
  }
}
async function handleAddBeam(){
  beamDiaLog.value.dialogVisible = true;
  beamDiaLog.value.title = t('functionService.add_beam_label', '新增波束');
  beamEditForm.value = {
    id: '',
    kd_name: '',
    downlink_freq: 0,
    ssb_position: 0,
    uplink_freq: 0,
    downlink_bdc: 0,
    uplink_buc: 0,
    sib1_downlink: 0,
    bandwidth: 0
  };
}

async function saveBeamEdit() {
  try {
    await beamEditFormRef.value.validate();
    beamDiaLog.value.dialogVisible = false;
    
    await NetworkAccessManagementApi.reqSetFrequencyPoint({
      sat: stateSelectNum.value,
      freq_info: [beamEditForm.value]
    });
    
    await getFrequencyPoint();
    ElNotificationFn('success', t('functionService.set_success_label'));
  } catch (error) {
    console.error('表单验证失败', error);
  }
}

let initTimer:any = null
const fetchTasks = [
    {fn:getBasebandInfo,name:'基带信息'},
    {fn:getStatus,name:'入网状态'},
    {fn:getAutoNetworkAccessStatus,name:'自动入网状态'},
    {fn:getDnnInfo,name:'DNN配置'},
  ]
async function init(){
  const results = await Promise.allSettled(
    fetchTasks.map(task => task.fn())
  )  
  results.forEach((result, index) => {
    if (result.status === 'rejected') {
      console.error(`获取${fetchTasks[index].name}失败:`, result.reason)
    }
  })
}
const apnConfig = ref<any>({
  apn:'',
  apnId:''
})
const appConfigRef = ref<any>(null)
const appConfigFormRules = ref<any>({
  apn:[
    {required:true,message:'apn不能为空',trigger:'blur'},
  ],
  apnId:[
    {required:true,message:'apnId不能为空',trigger:'blur'},
    {min:1,message:'apnId不能小于1',trigger:'blur'}
  ]
})
const appConfigList = ref<any>([])
async function addApnConfig(){
  try {
    await appConfigRef.value.validate()
    await BasicConfigApi.reqAddApnConfig({
      apn:apnConfig.value.apn,
      id:Number(apnConfig.value.apnId)
    })
    await getDnnList()
    ElNotificationFn('success', t('functionService.add_apn_success_label'))
  } catch (error) {
    ElNotificationFn('error', t('functionService.add_apn_failure_label'))
  }
}
async function deleteApnConfig(row:any){
  try {
    await BasicConfigApi.reqDeleteApnConfig({
      apn:row.apn
    })
    await getDnnList()
    ElNotificationFn('success', t('functionService.delete_apn_success_label'))
  } catch (error) {
    ElNotificationFn('error', t('functionService.delete_apn_failure_label'))
  }
}
const beaconFrequencyValue = ref(0)
const beaconFrequencyConfig = ref<any>({
  title:t('functionService.beacon_frequency_config_label'),
  subTitle:t('functionService.beacon_frequency_label'),
  component:'inputNumber',
  btns:[
    {
      label:t('functionService.set_label'),
      value:0,
      component:'Setting',
      type:'primary',
      loading:false,
      click:handleBeaconFrequencySet,
      class:"global_btn"
    }
  ]
})
async function handleBeaconFrequencySet(){
  await NetworkAccessManagementApi.reqSetBeaconFrequency({
    bc_freq:beaconFrequencyValue.value
  })
  ElNotificationFn('success', t('functionService.set_success_label'))
}
async function getBeaconFrequency(){
  const {data} = await NetworkAccessManagementApi.reqGetBeaconFrequency()
  beaconFrequencyValue.value = data.bc_freq
}
function scheduleNextUpdate(){
  initTimer = window.setTimeout(() => {
    init().finally(() => {
      if (initTimer) {
        scheduleNextUpdate()
      }
    })
  }, 3000)
}
const fetchTasks2 = [
  {fn:getBeaconFrequency,name:'信标频率'},
  {fn: getDnnConfig,name:'获取DNN配置'},
  {fn: getStateSelectConfig,name:'获取选星配置'},
  {fn: getSatelliteLongitude,name:'获取卫星经度'},
  {fn: getBeamConfig,name:'获取波束配置'},
  {fn: getFrequencyPoint,name:'获取频点配置'},
]
async function init2(){
  const results = await Promise.allSettled(
    fetchTasks2.map(task => task.fn())
  )  
  results.forEach((result, index) => {
    if (result.status === 'rejected') {
      console.error(`获取${fetchTasks2[index].name}失败:`, result.reason)
    }
  })
}
onActivated(()=>{
  init2()
  init()
  scheduleNextUpdate()
})
onDeactivated(()=>{
  if (initTimer) {
    clearTimeout(initTimer)
    initTimer = null
  }
})
</script>

<style scoped lang="scss">
@import '@/styles/input.scss';
@import '@/styles/card.scss';
@import '@/styles/table.scss';
@import '@/styles/switch.scss';
.network-access-management {
  padding: 20px;
  .container_left{
    .container_left_top{
      padding: 10px;
    }
    .container_left_bottom{
      padding: 10px;
      padding-bottom: 20px;
    }
  }
  .container_right{

  }
  .management-card {
    .card-header {
      display: flex;
      align-items: center;
      font-size: 16px;
      font-weight: 500;
      .el-icon {
        margin-right: 8px;
        font-size: 18px;
      }
    }
   
    .card-content {
      display: flex;
      align-items: center;
      padding: 20px;
      
      .switch-label {
        margin-right: 16px;
        font-size: 14px;
      }
      
      &.button-group {
        gap: 16px;
      }
      
      .el-input-number {
        margin-right: 16px;
        width: 180px;
      }
    }
  }
 
}

.title_box {
  display: flex;
  gap: 5px;
  align-items: center;
  img {
    width: 18px;
    height: 18px;
    display: block;
    vertical-align: middle;
  }
  span {
    line-height: 18px;
    display: inline-block;
    vertical-align: middle;
  }
}
.label_box{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  font-size: 14px;
}
:deep(.el-input-number.is-controls-right) {
  .el-input-number__decrease,
  .el-input-number__increase {
    background-color: var(--el-color-primary);
    border-color: var(--el-color-primary);  
    &:hover {
      background-color: var(--el-color-primary-light-3);
    }
    .el-icon {
      color: white;
    }
  }
}
.tech-form-item {
  position: relative;
  margin-bottom: 20px !important;
  :deep(.el-form-item__label) {
    font-size: 14px;
    color: #00b4ff;
    text-shadow: 0 0 5px rgba(0, 100, 255, 0.3);
    position: relative;
    padding-left: 16px;
    margin-bottom: 5px;
    &:before {
      content: '';
      position: absolute;
      left: 6px;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 14px;
      background: linear-gradient(to bottom, #00b4ff, transparent);
      border-radius: 2px;
    }
  }
  :deep(.el-input__wrapper) {
    background-color: rgba(0, 30, 60, 0.2);
    border: 1px solid rgba(0, 180, 255, 0.3);
    box-shadow: 0 0 5px rgba(0, 120, 215, 0.2);
    transition: all 0.3s;
    &:hover, &.is-focus {
      border-color: rgba(0, 180, 255, 0.8);
      box-shadow: 0 0 8px rgba(0, 180, 255, 0.4);
    }
    .el-input__inner {
      color: #e0f0ff;
  
    }
  }
  :deep(.el-select) {
    width: 100%;
  }
}
.tech-form {
  padding: 10px 0;
}
</style>
